<template>
  <div id="myDrawing" class="draw" style="background: #2c3e50;margin-top: 0px">
    <h1 style="color:Orange">图片标注网站</h1>
    <h4 style="color:Orange">在图片上拖动鼠标即可进行矩形框标注，已保存的标注框是蓝色的</h4>

    <div id="shape" class="label-shape">
              <el-tooltip class="item" effect="dark" content="矩形工具" placement="top"  style="margin-left: 2%">
                <svg width="45" height="25" style="margin:0px 0;float:left;" >
                  <rect x="0" y="0" width="45" height="25" style="fill:#e7f5ff;stroke:#96cffb;stroke-width:2px;cursor:pointer;" />
                </svg>
              </el-tooltip>
      <div>
        <el-button type="primary" @click="lastPhoto">上一张</el-button>
        <el-button type="danger" @click="resetALl">清除</el-button>
        <el-button type="primary" @click="cheXiao">撤销</el-button>
        <el-button type="primary" @click="nextPhoto">下一张</el-button>
        <el-button type="warning" @click="saveAndNext">完成</el-button>
        <el-button type="warning" @click="backtoHome">返回主页</el-button>
      </div>
    </div>
    <div>
      <div id="drawcanvas" style="margin-top: 5%;margin-bottom: 5%;">
        <img id="markingimg" :src="mysrc" style="width: 60%;height: 40%;display: none"/>
      </div>
      <canvas id="myCanvas"></canvas>
      <h4 style="color:Orange">在完成框选后，请在下方输入框中添加标签并点击“确定”保存</h4>
    </div>
    <div style="background: #96cffb;">
      <el-input v-model="currentLabel" placeholder="在此输入标签" style="margin-top: 3%;margin-bottom: 3%;width: 50%"></el-input>
      <el-button @click="this.nextLabel" >确认</el-button>
    </div>
    <div id="labels" v-for='(item, index) in markingLabel'>
      <div style="height: 14%">
        <span style="color: orange;float:left;margin-left: 5%;">标签{{index+1}}：{{mouse1[index]}}到{{mouse2[index]}}</span>
        <el-input type='text' v-model='markingLabel[index]' style="width: 30%;" :key='index'></el-input>
        <el-button type="danger" @click="deleteRecord(index)">删除</el-button>
      </div>
    </div>

  </div>
</template>
<script>
import svgJS from 'svg.js'
import 'svg.draw.js'
import 'svg.panzoom.js'
import 'svg.draggable.js'
import 'svg.draggy.js'
import 'svg.select.js'
import 'svg.resize.js'
import axios from "axios";
//在这定义鼠标事件与canvas对应的东西

export default {
  install: Vue => {
    Vue.prototype.$svg = svgJS
  },
  components: {},
  name: "ImageMarking",
  data() {
    return {
      // 图片的路径
      imageUrls: [],
      // 左上角和右下角的坐标
      mouse1: [],
      mouse2: [],
      isPainting: false,
      // 图片的宽和高
      imagew: 0,
      imageh: 0,
      //任务中图片的id
      imageIds: [],
      // 标注的文字
      markingLabel: [],
      // 现在图片标注的进度
      nowProgress: 0,
      // 总共需要标注的图片数量
      totalImages: 0,
      // 现在图片上的标记个数
      totalMarks: 0,
      // 当前展示的图片路径
      mysrc: "",
      // 当前的矩形两角位置、label内容
      currentLabel: "",
      currentmouse1: [0,0],
      currentmouse2: [0,0],
      unsaved: false,
      unUpload: false,
    }
  },

  // 在创建时需要请求后端还有哪些图片没有标注
  mounted: function () {
    axios.post('http://127.0.0.1:8000/imagemarking/ContinueTaskImage/', {
      token: window.sessionStorage.getItem("token")
    }).then((response) => {
      if (response.data.code === "200") {
        //渲染到页面上
        let datas = response.data.urls
        let ids = response.data.ids
        let count = 0
        for (let data in datas) {
          count++
          this.imageUrls.push(datas[data])
          this.imageIds.push(ids[data])
        }
        this.totalImages = count
        this.nowProgress = 0
        this.unUpload = true
        this.getImageWH()
      } else if (response.data.code === 100) {
        this.$alert(response.data.message)
        this.$router.push({path: "/MainPage"})
      } else {
        this.$router.push({path: "/LoginPage"})
      }
    })
  },

  methods: {
    // 清空当前画布内容
    resetALl() {
      console.log("resetall")
      this.totalMarks = 0
      this.currentLabel = ""
      this.clearCanvas()
      this.getImageWH()
      this.currentmouse1 = [0,0]
      this.currentmouse2 = [0,0]
    },
    // 撤销
    cheXiao() {
      this.mouse2.pop()
      this.mouse1.pop()
      this.markingLabel.pop()
      if (this.totalMarks > 0) {
        this.totalMarks--
      }
      this.resetALl()
    },
    //清空画布内容
    clearCanvas(){
      let c = document.getElementById("myCanvas")
      let cxt=c.getContext("2d");
      cxt.clearRect(0,0,c.width,c.height);
    },
    //画布创建
    imageOnCanvas(imageId) {
      this.clearCanvas()
      let canvas=document.getElementById("myCanvas");
      canvas.height = this.imageh
      canvas.width = this.imagew
      let ctx=canvas.getContext("2d");
      let img = document.getElementById("markingimg");
      ctx.drawImage(img,0,0)
      this.drawRecords()
      canvas.getContext("2d").fillStyle  = 'rgba(255,0,0,0.2)'
      canvas.getContext("2d").lineWidth = 3
      canvas.onmousedown = (e) =>{
        this.isPainting = true
        this.currentmouse1[0] = e.pageX - canvas.offsetLeft
        this.currentmouse1[1] = e.pageY - canvas.offsetTop
      }
      canvas.onmouseup = (e) => {
        this.isPainting = false
        this.currentmouse2[0] = e.pageX - canvas.offsetLeft
        this.currentmouse2[1] = e.pageY - canvas.offsetTop
        // 设置成红色透明矩形
        this.unsaved = true
        canvas.getContext("2d").strokeStyle = "red"
        canvas.getContext("2d").strokeRect(this.currentmouse1[0], this.currentmouse1[1], this.currentmouse2[0] - this.currentmouse1[0], this.currentmouse2[1] - this.currentmouse1[1])
      }
      canvas.onmousemove = (e) =>{
        if (this.isPainting){
          let x = e.pageX - canvas.offsetLeft
          let y = e.pageY - canvas.offsetTop
          canvas.getContext("2d").fillStyle  = 'rgba(255,0,0,0.01)'
          canvas.getContext("2d").fillRect(this.currentmouse1[0], this.currentmouse1[1], x - this.currentmouse1[0], y - this.currentmouse1[1])
        }
      }

    },
    //保存当前的矩形框位置、label内容,生成一个文本框对应
    nextLabel() {
      if (this.currentLabel == ""){
        this.$alert("请输入正确的标签内容")
        return;
      }
      if (this.unsaved)
      {
        console.log("save label")
        this.totalMarks++
        this.markingLabel.push(this.currentLabel)
        this.currentLabel = ""
        this.mouse1.push(this.currentmouse1)
        this.mouse2.push(this.currentmouse2)
        this.currentmouse2 = [0,0]
        this.currentmouse1 = [0,0]
        this.unsaved = false
        console.log("mouse1   "+this.mouse2)
        console.log(this.markingLabel)
        this.resetALl()
        return
      }
      else{
        this.$alert("没有需要保存的选框")
        return;
      }
    },
    //
    // 保存当前图片标注结果并发送到后端,后端将结果保存为文件并判断是否已经全部完成任务，若全部完成则返回code=666
    saveAndNext() {
      console.log(this.mouse1)
      console.log(this.mouse2)
      console.log(this.markingLabel)
      if (this.markingLabel.length < 1){
        this.$alert("你还没有进行标注!")
        return
      }
      axios.post(
        "http://127.0.0.1:8000/imagemarking/saveMarking/",
        {
          "mouse1": this.mouse1,
          "mouse2": this.mouse2,
          "id": this.imageIds[this.nowProgress],
          "width": this.imagew,
          "height": this.imageh,
          "labels": this.markingLabel
        }
      ).then(
        (response)=>{
          if (response.data.code === 200){
            this.$alert("成功保存标注结果!").then(this.$router.go(0))
            // 刷新本页
          }
          else{
            this.$alert("请求错误!")
          }
        }
      )


    },
    // 上一张标注
    lastPhoto() {
      if (this.nowProgress > 0) {
        this.nowProgress--
      }
      else{
        return
      }
      this.resetALl()
      this.getImageWH()
    },
    // 下一张标注
    nextPhoto() {
      if (this.nowProgress < this.totalImages - 1) {
        this.nowProgress++
      }
      else{
        return
      }
      this.resetALl()
      this.getImageWH()
    },
    backtoHome() {
      this.$router.push({path: "/MainPage"})
    },
    // 获取图片原生高度和宽度信息
    getImageWH() {
      let that = this
      this.mysrc = this.imageUrls[this.nowProgress]
      let img = new Image();
      img.src = this.imageUrls[this.nowProgress]
      img.onload = function(){
        that.imagew=img.width
        that.imageh=img.height
        that.imageOnCanvas(this.nowProgress)
      }
    },
    drawRecords(){
      // 将先前画的所有矩形渲染上去
      if (this.mouse1.length == 0)
      {
        return
      }
      let canvas=document.getElementById("myCanvas")
      for (let m in this.mouse1){
        let x1 = this.mouse1[m][0]
        let x2 = this.mouse2[m][0]
        let y1 = this.mouse1[m][1]
        let y2 = this.mouse2[m][1]
        canvas.getContext("2d").strokeStyle  = "blue"
        canvas.getContext("2d").strokeRect(x1, y1, x2-x1, y2-y1)
      }
    },
    //删除某个标记
    deleteRecord(index){
      this.mouse1.splice(index, 1)
      this.mouse2.splice(index, 1)
      this.markingLabel.splice(index, 1)
      this.totalMarks--
      this.resetALl()
    }
  }
}
</script>

<style scoped>

</style>
